package com.mysteel.product.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * ProjectName: mail
 * ClassName: MyCacheConfig
 * Description:
 * date: 2021/01/28/028 11:52
 *
 * @author xiaochao
 */

/**
 * 配置文件中的内容没生效
 * 1、原先和配置文件绑定的配置类写法：
 *      @ConfigurationProperties(prefix = "spring.cache")
 *      public class CacheProperties
 *      未将其注入到spring容器中
 * 2、要让它生效
 * 启用@EnableConfigurationProperties(CacheProperties.class)注解，将其与原先的配置类绑定
 * 使用方法：
 * 1、使用自动注入注解注入：
 *     @Autowired
 *     private CacheProperties cacheProperties;
 * 2、在@Bean注解的时候将其设置为参数，它会自动去容器中寻找并注入
 *     @Bean
 *     RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties)
 */
@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching
@Configuration
public class MyCacheConfig {

    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 修改key、value序列化机制
//        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));

        // 让配置文件中的配置生效
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}
